#include "./../../../include/online/Tools/Configuration.h"
#include "./../../../include/online/Tools/MyLogger.h"
#include <fstream>
#include <string.h>

Configuration *Configuration::_pInstance = nullptr; // 懒汉式
pthread_once_t Configuration::_once = PTHREAD_ONCE_INIT;

Configuration *Configuration::getInstance()
{
    pthread_once(&_once, init_r);
    return _pInstance;
}

// 读取配置文件
void Configuration::readConfigFile(const string &configFilePath)
{
    ifstream ifs(configFilePath);
    if (!ifs)
    {
        LogError("Error: Unable to open file " + configFilePath);
        LogError("Reason: " + strerror(errno));
        return;
    }

    string key, value;
    while (ifs >> key && getline(ifs, value))
    {
        // 去重value前面的一个空格
        if (!value.empty() && value[0] == ' ')
        {
            value = value.substr(1);
        }
        _configMap[key] = value;
    }

    LogInfo("readConfigFile");
    ifs.close();

    // 停用词表
    _stopWordList = getStopWordList();

    return;
}

// 获取配置文件中key对应的value
string Configuration::getMapValue(const string &key)
{
    auto it = _configMap.find(key);
    if (it == _configMap.end()) // 没查找到
    {
        LogError("Error: 无法找到key对应的value! ");
        return "";
    }
    return it->second;
}

// 获取配置文件内容
unordered_map<string, string> Configuration::getConfigMap()
{
    return _configMap;
}

Configuration::Configuration()
{

}
Configuration::~Configuration()
{
}

void Configuration::init_r()
{
    if (_pInstance == nullptr)
    {
        _pInstance = new Configuration();
        atexit(destory);
    }
}

void Configuration::destory()
{
    if (_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
}

unordered_set<string> Configuration::getStopWordList()
{
    // 读取英文停用库
    auto it = _configMap.find("stop_words_eng.txt");
    if (it != _configMap.end())
    {
        ifstream ifs((*it).second.c_str());
        string line;
        while (getline(ifs, line), !ifs.eof())
        {
            _stopWordList.insert(line);
        }
        ifs.close();
    }

    it = _configMap.find("stop_words_zh.txt");
    if (it != _configMap.end())
    {
        ifstream ifs((*it).second.c_str());
        string line;
        while (getline(ifs, line), !ifs.eof())
        {
            _stopWordList.insert(line);
        }
        ifs.close();
    }
    return _stopWordList;
}

bool Configuration::isStopWord(const string &word)
{
    auto it = _stopWordList.find(word);
    if (it == _stopWordList.end())
    {
        return false;
    }
    else
    {
        return true;
    }
}
